<?php

namespace App\Middleware;

use Core\Http\Request;
use Core\Http\Response;
use Core\Route\MiddlewareInterface;
use Core\Support\Redis;
use G\User\AuthService;
use G\User\Model\UserModel;

class Authenticate implements MiddlewareInterface
{
    protected $request;

    public function __construct()
    {
        $this->request = Request::getInstance();
    }

    public function handle()
    {
        if ($this->authenticate() !== true) {
            Response::getInstance()->fail(
                "认证已过期, 请重新登录",
                $this->request->getRequestId()
            );

            return false;
        }

        return true;
    }

    /**
     * 检查登录信息
     * token -> user
     */
    public function authenticate()
    {
        $token = $this->getToken();
        $user = $this->getLoginUser($token);

        // 检查账户是否有效
        if ($user && $user->isEnabled()) {
            AuthService::getInstance()
                ->setToken($token)
                ->setUser($user);

            return true;
        }

        return false;
    }


    /**
     * 获取用户
     */
    public function getLoginUser($token)
    {
        $uid = $this->getUid();
        if ($uid && UserModel::inTest($uid)) {
            return UserModel::find($uid);
        }

        // 通过Token获取用户
        if ($token) {
            $login = Redis::store(DXE_SESSION)->get($token);
            if ($login) {
                return UserModel::find($login['uid']);
            }
        }

        return null;
    }

    /**
     * Get Token
     */
    public function getToken()
    {
        $token = $this->request->header(APP_XATOKEN, '');

        return $token;
    }

    /**
     * Get Uid
     */
    public function getUid()
    {
        $uid = $this->request->header(APP_XAUID, '');

        return $uid;
    }
}